package com.local.mychess;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

public class ChessBoardView extends View {
    private static final String TAG = "ChessBoardView";
    private static final int BOARD_WIDTH = 9;
    private static final int BOARD_HEIGHT = 10;
    private int[][] chessBoard = new int[BOARD_WIDTH][BOARD_HEIGHT];
    private int selectedX = -1;
    private int selectedY = -1;
    private int selectedChess = 0;
    private int playerRole = 0; // 0:未分配, 1:红方, 2:黑方, 3:旁观者
    private int currentTurn = 1;
    private boolean landscape = false;
    private String redDeviceName = "";
    private String blackDeviceName = "";
    private int userCount = -1;

    private int keyboardX = -1;
    private int keyboardY = -1;
    private int margin_width = 100;
    private int margin_height = 200;

    private int usableWidth;
    private int usableHeight;
    private float cellWidth ;
    private float cellHeight;

    private Paint boardPaint;
    private Paint selectedPaint;
    private Paint keyboardPaint;


    private OnMoveListener moveListener;


    public interface OnMoveListener {
        void onMove(int fromX, int fromY, int toX, int toY);
        void onWarn();
        void onOutsizeFocus(int x);
    }

    public ChessBoardView(Context context) {
        super(context);
        init();
    }

    public ChessBoardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public int getPlayerRole() {
        return playerRole;
    }


    private void init() {
        setFocusable(true);
        setFocusableInTouchMode(true);

        // 初始化画笔
        boardPaint = new Paint();
        boardPaint.setColor(Color.BLACK);
        boardPaint.setStrokeWidth(2);
        boardPaint.setStyle(Paint.Style.STROKE);

        selectedPaint = new Paint();
        selectedPaint.setColor(Color.GREEN);
        selectedPaint.setStrokeWidth(6);
        selectedPaint.setStyle(Paint.Style.STROKE);

        keyboardPaint = new Paint();
        keyboardPaint.setColor(Color.BLUE);
        keyboardPaint.setStrokeWidth(6);
        keyboardPaint.setStyle(Paint.Style.STROKE);

        // 初始化棋盘
        resetBoard();

    }

    public int getCurrentTurn() {
        return currentTurn;
    }

    private static final String[] SAN_GUO_NAMES = {
            "刘备", "关羽", "张飞", "赵云", "马超",
            "黄忠", "曹操", "典韦", "许褚", "张辽",
            "徐晃", "郭嘉", "孙权", "周瑜", "鲁肃",
            "吕蒙", "陆逊", "吕布", "貂蝉", "袁术"
    };

    /**
     * 根据ID获取对应的显示名称（三国人名）
     * @param id 输入的ID字符串
     * @return 哈希映射后的三国人名
     */
    public static String getDisplayName(String id) {
        // 计算哈希值并确保为正数
        int hash = id.hashCode() & Integer.MAX_VALUE;

        // 哈希到20个人名范围内
        int index = hash % SAN_GUO_NAMES.length;

        return SAN_GUO_NAMES[index] + id.substring(id.length() - 3);
    }

    private String getChessName(int i) {
        switch (i) {
            case 1: return "帥";
            case 2: return "仕";
            case 3: return "仕";
            case 4: return "相";
            case 5: return "相";
            case 6: return "傌";
            case 7: return "傌";
            case 8: return "俥";
            case 9: return "俥";
            case 10: return "炮";
            case 11: return "炮";
            case 12: return "兵";
            case 13: return "兵";
            case 14: return "兵";
            case 15: return "兵";
            case 16: return "兵";
            case 17: return "將";
            case 18: return "士";
            case 19: return "士";
            case 20: return "象";
            case 21: return "象";
            case 22: return "馬";
            case 23: return "馬";
            case 24: return "車";
            case 25: return "車";
            case 26: return "砲";
            case 27: return "砲";
            case 28: return "卒";
            case 29: return "卒";
            case 30: return "卒";
            case 31: return "卒";
            case 32: return "卒";
        }
        return "";
    }

    public void resetBoard() {
        for (int i = 0; i < BOARD_WIDTH; i++) {
            for (int j = 0; j < BOARD_HEIGHT; j++) {
                chessBoard[i][j] = 0;
            }
        }
        chessBoard[4][9] = 1;    // 帅
        chessBoard[3][9] = 2;    // 仕
        chessBoard[5][9] = 3;    // 仕
        chessBoard[2][9] = 4;    // 相
        chessBoard[6][9] = 5;    // 相
        chessBoard[1][9] = 6;    // 马
        chessBoard[7][9] = 7;    // 马
        chessBoard[0][9] = 8;    // 车
        chessBoard[8][9] = 9;    // 车
        chessBoard[1][7] = 10;   // 炮
        chessBoard[7][7] = 11;   // 炮
        chessBoard[0][6] = 12;   // 兵
        chessBoard[2][6] = 13;   // 兵
        chessBoard[4][6] = 14;   // 兵
        chessBoard[6][6] = 15;   // 兵
        chessBoard[8][6] = 16;   // 兵

        chessBoard[4][0] = 17;   // 将
        chessBoard[3][0] = 18;   // 士
        chessBoard[5][0] = 19;   // 士
        chessBoard[2][0] = 20;   // 象
        chessBoard[6][0] = 21;   // 象
        chessBoard[1][0] = 22;   // 马
        chessBoard[7][0] = 23;   // 马
        chessBoard[0][0] = 24;   // 车
        chessBoard[8][0] = 25;   // 车
        chessBoard[1][2] = 26;   // 炮
        chessBoard[7][2] = 27;   // 炮
        chessBoard[0][3] = 32;   // 卒
        chessBoard[2][3] = 28;   // 卒
        chessBoard[4][3] = 29;   // 卒
        chessBoard[6][3] = 30;   // 卒
        chessBoard[8][3] = 31;   // 卒

        invalidate();
    }

    public void SetBoardAndRole(int current, String[] board, int role) {
        this.playerRole = role;
        SetBoard("", "", -1,-1, -1, current, board);
    }

    public void SetBoard(String redName, String blackName, int count,
                         int toX, int toY, int current, String[] board) {
        this.currentTurn = current;
        if (!redName.isEmpty()) {
            redDeviceName = redName;
        }
        if (!blackName.isEmpty()) {
            blackDeviceName = blackName;
        }
        if (count != -1) {
            userCount = count;
        }
        for (int y = 0; y < BOARD_HEIGHT; y++) {
            for (int x = 0; x < BOARD_WIDTH; x++) {
                chessBoard[x][y] = Integer.parseInt(board[y * BOARD_WIDTH + x]);
            }
        }
        if (toX >= 0 && toX < BOARD_WIDTH && toY >= 0 && toY < BOARD_HEIGHT) {
            selectedX = toX;
            selectedY = toY;
            if (current < 3 && isInCheck()) {
                if (moveListener != null) {
                    moveListener.onWarn();
                }
            }
        }

        invalidate();
    }



    public void setOnMoveListener(OnMoveListener listener) {
        this.moveListener = listener;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int viewWidth = this.getMeasuredWidth();
        int viewHegith = this.getMeasuredHeight();
        if (viewWidth <= 0 || viewHegith <= 0) {
            return;
        }
        if (viewWidth > viewHegith) {
            landscape = true;
        } else {
            landscape = false;
        }

        if (landscape) {
            margin_width = 600;
            margin_height = 100;
        } else {
            margin_width = 100;
            margin_height = 200;
        }
        // 计算可用空间
        usableWidth = viewWidth - 2 * margin_width;
        usableHeight = viewHegith - 2 * margin_height;

        // 计算单元格尺寸（矩形，不强制正方形）
        cellWidth = (float) usableWidth / (BOARD_WIDTH - 1);
        cellHeight = (float) usableHeight / (BOARD_HEIGHT - 1);

        drawBoard(canvas);
        drawPieces(canvas);
        drawSelection(canvas);
        drawResult(canvas);
    }

    public void drawBoard(Canvas canvas) {
        // 初始化画笔
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(0xFF000000); // 黑色线条
        paint.setStrokeWidth(4);
        paint.setStyle(Paint.Style.STROKE);

        // 绘制横线
        for (int i = 0; i < BOARD_HEIGHT; i++) {
            float y = margin_height + i * cellHeight;
            canvas.drawLine(margin_width, y, margin_width + usableWidth, y, paint);
        }

        // 绘制竖线
        for (int i = 0; i < BOARD_WIDTH; i++) {
            float x = margin_width + i * cellWidth;
            if (i == 0 || i == BOARD_WIDTH - 1) {
                canvas.drawLine(x, margin_height, x, margin_height + usableHeight, paint);
            } else {
                canvas.drawLine(x, margin_height,
                        x, margin_height + 4 * cellHeight,
                        paint);
                canvas.drawLine(x, margin_height + 5 * cellHeight,
                        x, margin_height + usableHeight,
                        paint);
            }
        }

        // 绘制楚河汉界文字
        paint.setStyle(Paint.Style.FILL);
        // 不使用DEFAULT_BOLD，保持默认字体样式
        float textSize = Math.min(cellWidth, cellHeight) * 0.6f;
        paint.setTextSize(textSize);
        paint.setTextAlign(Paint.Align.CENTER);

        // 计算文字垂直位置
        float textY = margin_height + 4 * cellHeight + cellHeight * 3 / 5;

        // 绘制楚河
        canvas.drawText("楚河", margin_width + 2 * cellWidth, textY, paint);
        // 绘制汉界
        canvas.drawText("汉界", margin_width + 6 * cellWidth, textY, paint);

        // 重置画笔样式绘制九宫格斜线
        paint.setStyle(Paint.Style.STROKE);

        // 红方九宫格斜线
        canvas.drawLine(
                margin_width + 3 * cellWidth, margin_height,
                margin_width + 5 * cellWidth, margin_height + 2 * cellHeight,
                paint
        );
        canvas.drawLine(
                margin_width + 5 * cellWidth, margin_height,
                margin_width + 3 * cellWidth, margin_height + 2 * cellHeight,
                paint
        );

        // 黑方九宫格斜线
        canvas.drawLine(
                margin_width + 3 * cellWidth, margin_height + 7 * cellHeight,
                margin_width + 5 * cellWidth, margin_height + 9 * cellHeight,
                paint
        );
        canvas.drawLine(
                margin_width + 5 * cellWidth, margin_height + 7 * cellHeight,
                margin_width + 3 * cellWidth, margin_height + 9 * cellHeight,
                paint
        );
    }

    public void drawChess(Canvas canvas, int x, int y, String name, int color) {

        // 初始化画笔
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setAntiAlias(true); // 抗锯齿，使圆形更平滑

        // 计算棋子的实际半径（取宽高中最小值的一半，确保为圆形）
        int radius = (int)Math.min(cellWidth, cellHeight) / 2;

        // 计算棋子中心点坐标（外框的中心）
        int centerX = margin_width + (int)(x * cellWidth);
        int centerY = margin_height + (int)(y * cellHeight);

        // 绘制棋子圆形（实心）
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(centerX, centerY, radius, paint);

        if (color == 0) {
            // 红色棋子
            paint.setColor(Color.RED);
        } else {
            // 黑色棋子
            paint.setColor(Color.BLACK);
        }
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.STROKE);
        if (DeviceInfor.getIsPadMode()) {
            if (color == 1) {
                paint.setStyle(Paint.Style.FILL);
            }
        }
        canvas.drawCircle(centerX, centerY, radius, paint);

        if (DeviceInfor.getIsPadMode()) {
            if (color == 1) {
                // 绘制棋子内部文字（白色）
                paint.setColor(Color.WHITE);
            }
        }
        paint.setStyle(Paint.Style.FILL);
        // 文字大小为半径的0.7倍，确保在圆形内合适显示
        paint.setTextSize(radius * 1.2f);
        // 文字水平居中
        paint.setTextAlign(Paint.Align.CENTER);

        // 计算文字垂直居中的基线
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        float textBaseline = centerY - (fontMetrics.top + fontMetrics.bottom) / 2;

        // 绘制棋子名称
        canvas.drawText(name, centerX, textBaseline, paint);
    }

    private void drawPieces(Canvas canvas) {
        for (int y = 0; y < BOARD_HEIGHT; y++) {
            //String output = y + ":";
            for (int x = 0; x < BOARD_WIDTH; x++) {
                int piece = chessBoard[x][y];
                //output += (piece + ",");
                if (piece != 0) {
                    int color = piece > 16?1:0;
                    drawChess(canvas, x, y,  getChessName(piece), color);
                }
            }
            //Log.d(TAG, output);
        }
    }

    private void drawSelection(Canvas canvas) {
        if (selectedX != -1 && selectedY != -1) {
            drawRect(canvas, selectedX, selectedY, selectedPaint, 0);
        }
        if (keyboardX != -1 && keyboardY != -1) {
            drawRect(canvas, keyboardX, keyboardY, keyboardPaint, 6);
        }
    }

    private void drawRect(Canvas canvas, int x, int y, Paint paint, int margin) {
        int centerX = margin_width + (int)(x * cellWidth);
        int centerY = margin_height + (int)(y * cellHeight);
        int radius = (int)Math.min(cellWidth, cellHeight) / 2 - margin;
        int left = centerX - radius;
        int right = centerY - radius;
        canvas.drawRect(left,
                right,
                left + 2*radius,
                right + 2*radius,
                paint);
    }

    private void drawResult(Canvas canvas) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(0xFF000000); // 黑色线条
        paint.setStrokeWidth(4);
        paint.setStyle(Paint.Style.STROKE);

        String playerAction = "旁观";
        if (playerRole == 1) {
            playerAction = "执红";
        } else if (playerRole == 2) {
            playerAction = "执黑";
        }
        String playerInfo;
        if (userCount > 0) {
            playerInfo = String.format("%s(%s) 共%d人",
                    getDisplayName(DeviceInfor.getLocalID()),
                    playerAction, userCount);
        } else {
            playerInfo = String.format("%s(%s)",
                    getDisplayName(DeviceInfor.getLocalID()),
                    playerAction);
        }

        String currentStepInfo = "";
        String currentResult = "";
        switch (this.currentTurn) {
            case 1:
                currentStepInfo = "红方回合";
                break;
            case 2:
                currentStepInfo = "黑方回合";
                break;
            case 3:
                currentStepInfo = "红方胜利";
                if (playerRole == 1) {
                    currentResult = "胜利";
                } else if (playerRole == 2) {
                    currentResult = "失败";
                }
                break;
            case 4:
                currentStepInfo = "黑方胜利";
                if (playerRole == 2) {
                    currentResult = "胜利";
                } else if (playerRole == 1) {
                    currentResult = "失败";
                }
                break;
        }

        paint.setStyle(Paint.Style.FILL);

        float textSize = Math.min(cellWidth, cellHeight) * 0.3f;


        if (landscape) {
            //横屏
            textSize = (float)(textSize * 1.5);
            paint.setTextSize(textSize);
            float blackY = margin_height;
            float redY = margin_height + (float)(9.5 * cellHeight) - textSize;

            canvas.drawText(playerInfo,
                    (float)margin_width /3 ,
                    blackY + cellHeight,
                    paint);

            canvas.drawText(currentStepInfo,
                    (float)margin_width /3 ,
                    blackY + 2 * cellHeight,
                    paint);

            if (!blackDeviceName.isEmpty()) {
                canvas.drawText("黑:" + getDisplayName(blackDeviceName),
                        (float)margin_width /3 ,
                        blackY,
                        paint);
            }

            if (!redDeviceName.isEmpty()) {
                canvas.drawText("红:" + getDisplayName(redDeviceName),
                        (float)margin_width /3 ,
                        redY,
                        paint);
            }

            // 显示胜负
            if (!currentResult.isEmpty()) {
                paint.setTextSize(textSize * 5);
                if (playerRole == 1) {
                    paint.setColor(Color.RED);
                    canvas.drawText(currentResult,
                            margin_width + (int)(3.5 * cellWidth),
                            margin_height + 8 * cellHeight,
                            paint);
                } else if (playerRole == 2) {
                    paint.setColor(Color.BLACK);
                    canvas.drawText(currentResult,
                            margin_width + (int)(3.5 * cellWidth),
                            margin_height + 2 * cellHeight,
                            paint);
                }
            }
        } else {
            //竖屏
            paint.setTextSize(textSize);
            float blackY = Math.max(0, margin_height - 3 * textSize);
            float redY = usableHeight + margin_height +
                    (float)(Math.min(cellHeight * 2 / 3, margin_height - textSize));

            if (DeviceInfor.getIsPadMode()) {
                redY += textSize;
            }
            canvas.drawText( playerInfo + " - " + currentStepInfo,
                    margin_width + 2 * cellWidth,
                    redY,
                    paint);

            if (!blackDeviceName.isEmpty()) {
                canvas.drawText("黑:" + getDisplayName(blackDeviceName),
                        Math.max(10, margin_width - textSize),
                        blackY,
                        paint);
            }
            if (!redDeviceName.isEmpty()) {
                canvas.drawText("红:" + getDisplayName(redDeviceName),
                        Math.max(10, margin_width - textSize),
                        redY,
                        paint);
            }

            //显示胜负
            if (!currentResult.isEmpty()) {
                paint.setTextSize(textSize * 5);
                if (playerRole == 1) {
                    paint.setColor(Color.RED);
                    canvas.drawText(currentResult,
                            margin_width + (int)(2.5 * cellWidth),
                            margin_height + 8 * cellHeight,
                            paint);
                } else if (playerRole == 2) {
                    paint.setColor(Color.BLACK);
                    canvas.drawText(currentResult,
                            margin_width + (int)(2.5 * cellWidth),
                            margin_height + 2 * cellHeight,
                            paint);
                }
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // 计算点击位置对应的棋盘坐标
            int x = (int)((event.getX() - margin_width + cellWidth/2) / cellWidth);
            int y = (int)((event.getY() - margin_height + cellHeight/2) / cellHeight);
            Log.d(TAG, "touch:" + x + "," + y);
            handleBoardTouch(x, y);
            keyboardX = -1;
            keyboardY = -1;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyboardX == -1 || keyboardY == -1) {
            keyboardX = 0;
            keyboardY = 0;
            return super.onKeyDown(keyCode, event);
        }

        // 处理方向键移动选择
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (moveListener != null) {
                    moveListener.onOutsizeFocus(keyboardX);
                }
                return true;
            case KeyEvent.KEYCODE_DPAD_UP:
                if (keyboardY > 0) {
                    keyboardY--;
                }
                invalidate();
                return true;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                if (keyboardY < BOARD_HEIGHT - 1) {
                    keyboardY++;
                    invalidate();
                } else {
                    if (moveListener != null) {
                        moveListener.onOutsizeFocus(keyboardX);
                    }
                }
                return true;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (keyboardX > 0) {
                    keyboardX--;
                }
                invalidate();
                return true;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (keyboardX < BOARD_WIDTH - 1) {
                    keyboardX++;
                }
                invalidate();
                return true;
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_DPAD_CENTER:
                handleBoardTouch(keyboardX, keyboardY);
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void handleBoardTouch(int x, int y) {
        if (playerRole != 1 && playerRole != 2) {
            return;
        }
        if (x >= BOARD_WIDTH || y >= BOARD_HEIGHT) {
            return;
        }
        int piece = chessBoard[x][y];
        if (piece == 0) {
            //如果当前位置没有棋子
            if (selectedX == -1 && selectedY == -1) {
                //无意义
                return;
            } else {
                //检查能否走到这个位置
                if (canMove(selectedChess, selectedX, selectedY, x, y)) {
                    if (moveListener != null) {
                        moveListener.onMove(selectedX, selectedY, x, y);
                    }
                }
            }
        } else {
            //如果当前位置有棋子
            if (selectedX == -1 && selectedY == -1) {
                if ((playerRole == 1 && piece >= 1 && piece <= 16) ||
                        (playerRole == 2 && piece >= 17 && piece <= 32)) {
                    //如果是自家棋子，则选择该棋子
                    selectedX = x;
                    selectedY = y;
                    selectedChess = piece;
                    invalidate();
                }
            } else {
                if ((playerRole == 1 && piece >= 1 && piece <= 16) ||
                        (playerRole == 2 && piece >= 17 && piece <= 32)) {
                    //如果是自家棋子，则选择该棋子
                    selectedX = x;
                    selectedY = y;
                    selectedChess = piece;
                    invalidate();
                } else {
                    //检查能否走到这个位置
                    if (canMove(selectedChess, selectedX, selectedY, x, y)) {
                        if (moveListener != null) {
                            moveListener.onMove(selectedX, selectedY, x, y);
                        }
                    }
                }
            }
        }
    }

    public boolean isInCheck() {
        int kingX = -1, kingY = -1;    // 帅的位置
        int generalX = -1, generalY = -1;  // 将的位置

        for (int x = 0; x < BOARD_WIDTH; x++) {
            for (int y = 0; y < BOARD_HEIGHT; y++) {
                if (chessBoard[x][y] == 1) {  // 找到帅
                    kingX = x;
                    kingY = y;
                } else if (chessBoard[x][y] == 17) {  // 找到将
                    generalX = x;
                    generalY = y;
                }
            }
        }

        // 如果未找到帅或将，不可能形成将军
        if (kingX == -1 || generalX == -1) {
            return false;
        }

        // 检查红方棋子是否威胁到黑方将
        if (isKingThreatened(generalX, generalY, 17)) {
            return true;
        }

        // 检查黑方棋子是否威胁到红方帅
        if (isKingThreatened(kingX, kingY, 1)) {
            return true;
        }

        return false;
    }

    private boolean isKingThreatened(int kingX, int kingY, int kingValue) {
        // 遍历棋盘上所有对方棋子
        for (int x = 0; x < BOARD_WIDTH; x++) {
            for (int y = 0; y < BOARD_HEIGHT; y++) {
                int piece = chessBoard[x][y];
                if (piece == 0) continue;  // 空位置跳过

                // 判断是否为对方棋子
                boolean isEnemy;
                if (kingValue == 1) {
                    // 帅(红方)的敌人是黑方棋子(17-32)
                    isEnemy = piece >= 22 && piece <= 32;
                } else {
                    // 将(黑方)的敌人是红方棋子(1-16)
                    isEnemy = piece >= 6 && piece <= 16;
                }

                if (isEnemy) {
                    // 需要能移动到
                    if (!canMove(piece, x, y, kingX, kingY)) {
                        continue;
                    }
                    // 如果是炮，中间要有且只有1个间隔
                    if (piece == 10 || piece == 11 || piece == 26 || piece == 27) {
                        int obstacleCount = getObstacleCount(x, y, kingX, kingY);
                        if (obstacleCount != 1) {
                            continue;
                        }
                    }

                    Log.d(TAG, String.format("attack %d %d -> %d %d", kingX, kingY, x, y));
                    return true;
                }
            }
        }
        return false;
    }

    // 帅将面对面
    private boolean isAgainstKing(int startx, int starty, int targetx, int targety) {
        // 首先复制当前棋盘状态，模拟走棋后的情况
        int[][] tempBoard = new int[BOARD_WIDTH][BOARD_HEIGHT];
        for (int i = 0; i < BOARD_WIDTH; i++) {
            System.arraycopy(chessBoard[i], 0, tempBoard[i], 0, BOARD_HEIGHT);
        }

        // 模拟移动棋子
        int piece = tempBoard[startx][starty];
        tempBoard[targetx][targety] = piece;
        tempBoard[startx][starty] = 0;

        // 查找帅(1)和将(17)的位置
        int kingX = -1, kingY = -1;    // 帅的位置
        int generalX = -1, generalY = -1;  // 将的位置

        for (int x = 0; x < BOARD_WIDTH; x++) {
            for (int y = 0; y < BOARD_HEIGHT; y++) {
                if (tempBoard[x][y] == 1) {  // 找到帅
                    kingX = x;
                    kingY = y;
                } else if (tempBoard[x][y] == 17) {  // 找到将
                    generalX = x;
                    generalY = y;
                }
            }
        }

        // 如果未找到帅或将，不可能形成对帅
        if (kingX == -1 || generalX == -1) {
            return false;
        }

        // 检查是否在同一列(x坐标相同)
        if (kingX != generalX) {
            return false;
        }

        // 检查将帅之间是否有棋子阻隔
        int minY = Math.min(kingY, generalY);
        int maxY = Math.max(kingY, generalY);

        for (int y = minY + 1; y < maxY; y++) {
            if (tempBoard[kingX][y] != 0) {
                // 有棋子阻隔，不会形成对帅
                return false;
            }
        }

        // 所有条件都满足，形成了将帅对面
        return true;
    }

    public boolean canMove(int chessValue, int startx, int starty, int targetx, int targety) {
        // 1. 基础有效性检查
        if (startx == targetx && starty == targety) {
            return false; // 起始位置与目标位置相同
        }
        if (isSameSide(chessValue, chessBoard[targetx][targety])) {
            return false; // 目标位置有己方棋子
        }

        // 2. 防止对帅
        if (isAgainstKing(startx, starty, targetx, targety)) {
            return false;
        }

        // 3. 根据棋子类型检查走法
        switch (chessValue) {
            case 1:  // 帅
                return isValidKingMove(startx, starty, targetx, targety);
            case 17: // 将
                return isValidKingMove(startx, starty, targetx, targety);
            case 2: case 3:  // 仕
                return isValidAdvisorMove(startx, starty, targetx, targety, true);
            case 18: case 19: // 士
                return isValidAdvisorMove(startx, starty, targetx, targety, false);
            case 4: case 5:   // 相
                return isValidElephantMove(startx, starty, targetx, targety, true);
            case 20: case 21: // 象
                return isValidElephantMove(startx, starty, targetx, targety, false);
            case 6: case 7: case 22: case 23: // 马
                return isValidHorseMove(startx, starty, targetx, targety);
            case 8: case 9: case 24: case 25: // 车
                return isValidChariotMove(startx, starty, targetx, targety);
            case 10: case 11: case 26: case 27: // 炮
                return isValidCannonMove(startx, starty, targetx, targety);
            case 12: case 13: case 14: case 15: case 16: // 兵
                return isValidPawnMove(startx, starty, targetx, targety, true);
            case 28: case 29: case 30: case 31: case 32: // 卒
                return isValidPawnMove(startx, starty, targetx, targety, false);
            default:
                return false; // 未知棋子
        }
    }


    /**
     * 检查目标位置是否是己方棋子
     */
    private boolean isSameSide(int currentValue, int targetValue) {
        if (targetValue == 0) return false; // 目标位置为空

        // 红方棋子范围：1-16
        boolean currentIsRed = currentValue >= 1 && currentValue <= 16;
        // 黑方棋子范围：17-32
        boolean targetIsRed = targetValue >= 1 && targetValue <= 16;

        return currentIsRed == targetIsRed;
    }

    /**
     * 帅/将走法检查（九宫格内一步直线移动）
     */
    private boolean isValidKingMove(int startx, int starty, int targetx, int targety) {
        // 检查是否在九宫格内
        if (!isInPalace(startx, starty) || !isInPalace(targetx, targety)) {
            return false;
        }

        // 检查是否是一步直线移动（上下左右）
        int dx = Math.abs(targetx - startx);
        int dy = Math.abs(targety - starty);
        return (dx == 1 && dy == 0) || (dx == 0 && dy == 1);
    }

    /**
     * 检查是否在九宫格内
     */
    private boolean isInPalace(int x, int y) {
        // 红方九宫（下方）：x=3-5, y=7-9
        boolean inRedPalace = x >= 3 && x <= 5 && y >= 7 && y <= 9;
        // 黑方九宫（上方）：x=3-5, y=0-2
        boolean inBlackPalace = x >= 3 && x <= 5 && y >= 0 && y <= 2;
        return inRedPalace || inBlackPalace;
    }

    /**
     * 仕/士走法检查（九宫格内一步对角线）
     */
    private boolean isValidAdvisorMove(int startx, int starty, int targetx, int targety, boolean isRed) {
        // 检查是否在对应方的九宫格内
        if (isRed) {
            if (!(startx >= 3 && startx <= 5 && starty >= 7 && starty <= 9) ||
                    !(targetx >= 3 && targetx <= 5 && targety >= 7 && targety <= 9)) {
                return false;
            }
        } else {
            if (!(startx >= 3 && startx <= 5 && starty >= 0 && starty <= 2) ||
                    !(targetx >= 3 && targetx <= 5 && targety >= 0 && targety <= 2)) {
                return false;
            }
        }

        // 检查是否是一步对角线移动
        int dx = Math.abs(targetx - startx);
        int dy = Math.abs(targety - starty);
        return dx == 1 && dy == 1;
    }

    /**
     * 相/象走法检查（田字格，不能过河，检查象眼）
     */
    private boolean isValidElephantMove(int startx, int starty, int targetx, int targety, boolean isRed) {
        // 检查是否过河（相/象不能过河）
        if (isRed) {
            if (starty < 5 || targety < 5) return false; // 红相不能过河（y<5为对方区域）
        } else {
            if (starty > 4 || targety > 4) return false; // 黑象不能过河（y>4为对方区域）
        }

        // 检查是否是田字格移动
        int dx = Math.abs(targetx - startx);
        int dy = Math.abs(targety - starty);
        if (dx != 2 || dy != 2) {
            return false;
        }

        // 检查象眼是否被塞住（田字格中心是否有棋子）
        int eyeX = startx + (targetx - startx) / 2;
        int eyeY = starty + (targety - starty) / 2;
        return chessBoard[eyeX][eyeY] == 0;
    }

    /**
     * 马走法检查（日字格，检查马脚）
     */
    private boolean isValidHorseMove(int startx, int starty, int targetx, int targety) {
        int dx = Math.abs(targetx - startx);
        int dy = Math.abs(targety - starty);

        // 检查是否是日字格移动
        if (!((dx == 1 && dy == 2) || (dx == 2 && dy == 1))) {
            return false;
        }

        // 检查马脚是否被绊住
        if (dx == 2) {
            // 横向移动2格，检查中间纵向马脚
            int footX = startx + (targetx > startx ? 1 : -1);
            int footY = starty;
            return chessBoard[footX][footY] == 0;
        } else {
            // 纵向移动2格，检查中间横向马脚
            int footX = startx;
            int footY = starty + (targety > starty ? 1 : -1);
            return chessBoard[footX][footY] == 0;
        }
    }

    /**
     * 车走法检查（直线移动，不能越子）
     */
    private boolean isValidChariotMove(int startx, int starty, int targetx, int targety) {
        // 检查是否是直线移动（横向或纵向）
        if (startx != targetx && starty != targety) {
            return false;
        }

        // 检查路径上是否有棋子阻挡
        if (startx == targetx) {
            // 纵向移动
            int minY = Math.min(starty, targety);
            int maxY = Math.max(starty, targety);
            for (int y = minY + 1; y < maxY; y++) {
                if (chessBoard[startx][y] != 0) {
                    return false; // 路径有棋子阻挡
                }
            }
        } else {
            // 横向移动
            int minX = Math.min(startx, targetx);
            int maxX = Math.max(startx, targetx);
            for (int x = minX + 1; x < maxX; x++) {
                if (chessBoard[x][starty] != 0) {
                    return false; // 路径有棋子阻挡
                }
            }
        }
        return true;
    }

    /**
     * 炮走法检查（直线移动，吃子需翻山）
     */
    private boolean isValidCannonMove(int startx, int starty, int targetx, int targety) {
        // 检查是否是直线移动（横向或纵向）
        if (startx != targetx && starty != targety) {
            return false;
        }
        int obstacleCount = getObstacleCount(startx, starty, targetx, targety);

        // 炮的规则：不吃子时路径无棋子，吃子时路径有且仅有一个棋子
        int targetValue = chessBoard[targetx][targety];
        if (targetValue == 0) {
            return obstacleCount == 0; // 不吃子，路径必须无棋子
        } else {
            return obstacleCount == 1; // 吃子，路径必须有一个棋子（翻山）
        }
    }

    private int getObstacleCount(int startx, int starty, int targetx, int targety) {
        // 统计路径上的棋子数量（炮翻山用）
        int obstacleCount = 0;

        if (startx == targetx) {
            // 纵向移动
            int minY = Math.min(starty, targety);
            int maxY = Math.max(starty, targety);
            for (int y = minY + 1; y < maxY; y++) {
                if (chessBoard[startx][y] != 0) {
                    obstacleCount++;
                }
            }
        } else {
            // 横向移动
            int minX = Math.min(startx, targetx);
            int maxX = Math.max(startx, targetx);
            for (int x = minX + 1; x < maxX; x++) {
                if (chessBoard[x][starty] != 0) {
                    obstacleCount++;
                }
            }
        }
        return obstacleCount;
    }

    /**
     * 兵/卒走法检查（过河前后走法不同）
     */
    private boolean isValidPawnMove(int startx, int starty, int targetx, int targety, boolean isBlack) {
        int dx = Math.abs(targetx - startx);
        int dy = targety - starty;

        if (!isBlack) {
            // 红兵（向上为负方向）
            if (starty < 5) {
                return dx == 0 && dy == 1; // 只能向下走一步
            } else {
                // 过河后：可以左右走一步或向前走一步
                return (dx == 1 && dy == 0) || (dx == 0 && dy == 1);
            }
        }
        else {
            // 未过河（y > 4）：只能向上（y减小方向）走一步
            if (starty > 4) {
                return dx == 0 && dy == -1; // 只能向上走一步
            } else {
                // 过河后：可以左右走一步或向前走一步
                return (dx == 1 && dy == 0) || (dx == 0 && dy == -1);
            }
        }
    }
}